package com.yuelao.thread.demo;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

/**
 * 线程间通信
 * 管道输入、输出流
 * Created by fengliye on 2017/10/6.
 */
public class ThreadDemo2 {
    public static void main(String[] args) throws Exception {
        PipedWriter writer = new PipedWriter();
        PipedReader reader = new PipedReader();
        writer.connect(reader);
        Thread print = new Thread(new Print(reader), "Print");
        print.start();
        int receive = 0;
        try {
            while((receive = System.in.read()) != -1) {
                writer.write(receive);
            }
        } finally {
            writer.close();
        }
    }

    /**
     * 字节流
     */
    static class Print implements Runnable{
        private PipedReader read;
        public Print(PipedReader read) {
            this.read = read;
        }

        @Override
        public void run() {
            int receive = 0;
            try {
                while((receive = read.read()) != -1) {
                    System.out.println((char) receive);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
